package com.waiting.leetcode;

import java.util.Arrays;

/**
 * @Description
 * @Author bjweitingting
 * @Date 2019/2/27
 **/
public class ThreeSumClosest16 {
    public static void main(String[] args) {

    }

    public int threeSumClosest2(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];
        int sum;
        for (int i = 0; i < nums.length - 2; i++) {
            int j = i + 1, k = nums.length - 1;
            while (j < k) {
                sum = nums[i] + nums[j] + nums[k];
                if (sum == target) {
                    return sum;
                } else {
                    if (Math.abs(result - target) > Math.abs(sum - target)) {
                        result = sum;
                    }
                    if (sum < target) {
                        j++;
                    } else {
                        k--;
                    }
                }
            }
        }
        return result;
    }

    public int threeSumClosest(int[] nums, int target) {
        if (nums.length < 3) {
            return 0;
        }
        int res = 0;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = i + 1; j < nums.length - 1; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    int t = nums[i] + nums[j] + nums[k];
                    int temp = Math.abs((target - t));
                    if (t == target) {
                        return t;
                    }  else if (temp < min) {
                        min = temp;
                        res = t;
                    }
                }
            }
        }
        return res;
    }
}